/**
 * 可视化本地存储，使用localforage（更大存储空间）
 * =============================
 */
import { getPageId } from '@/utils/util-common';
import driverStorage from './driverStorage';

const storage = {
  isInited: false,
  localforage: null,

  init() {
    if (this.isInited) {
      return;
    }
    this.isInited = true;
    this.localforage = new driverStorage({
      name: 'visualComp',
      storeName: 'visualStore',
    });
    this.clearTimeoutItems();
  },

  getKey(key, limitBy = 'page', hasTimeout = false) {
    const pageId = getPageId();
    const { tenantId } = window._adoPremise;
    let _key;
    if (limitBy === 'page') {
      _key = `${tenantId}_${pageId}_${key}`; // 当前页面内有效
    } else if (limitBy === 'tenant') {
      _key = `${tenantId}_${key}`; // 当前租户有效
    } else if (limitBy === 'domain') {
      _key = key; // 当前域名有效
    } else {}

    // 有缓存时间的可以加前缀t_
    if (hasTimeout) {
      _key = `t_${_key}`;
    }

    return _key;
  },

  setItem(key, val, limitBy = 'page', timeout = 0) {
    const _key = this.getKey(key, limitBy, timeout > 0);
    let _val = val;
    if (timeout) {
      _val = { value: val, expireTime: Date.now() + timeout };
    }
    return this.localforage.setItem(_key, _val);
  },

  async getItem(key, limitBy = 'page', hasTimeout = false) {
    const _key = this.getKey(key, limitBy, hasTimeout);
    const _val = await this.localforage.getItem(_key);
    if (_val?.expireTime) {
      if (_val.expireTime < Date.now()) {
        this.localforage.removeItem(_key);
        return null;
      }
      return _val.value;
    }
    return _val;
  },

  removeItem(key, limitBy = 'page', hasTimeout = false) {
    const _key = this.getKey(key, limitBy, hasTimeout);
    return this.localforage.removeItem(_key);
  },

  keys(limitBy = 'page') {
    const keyPre = this.getKey('', limitBy);
    return this.localforage.keys().then(keys => keys.map(n => n.indexOf(keyPre === 0)));
  },

  // 清空单个过期的缓存
  async deleteTimeoutItem(_key) {
    if (_key.startsWith('t_')) {
      const val = await this.localforage.getItem(_key);
      if (val?.expireTime && val.expireTime < Date.now()) {
        this.localforage.removeItem(_key);
      }
    }
  },

  // 清空所有过期的缓存
  clearTimeoutItems() {
    this.localforage.keys().then(keys => {
      keys.forEach(_key => {
        this.deleteTimeoutItem(_key);
      });
    });
  },

};
storage.init();

export default storage;
